package com.xing.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xing.cmn.entity.Dict;
import com.xing.cmn.listener.DictListener;
import com.xing.cmn.mapper.DictMapper;
import com.xing.cmn.service.DictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xing.hospital.model.vo.cmn.DictEevo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 组织架构表 服务实现类
 * </p>
 *
 * @author xingfuao
 * @since 2022-05-16
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    private static final Logger LOG = LoggerFactory.getLogger(DictServiceImpl.class);

    @Autowired
    private DictMapper dictMapper;

    /**
     * 根据数据id查询子数据列表
     *
     * @param id
     * @return
     */

    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    @Override
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);

        List<Dict> dictList = baseMapper.selectList(wrapper);


//        if (!CollectionUtils.isEmpty(dictList)) {
//            LOG.info("数据字典的数据_dictList:{}", dictList);
//        }

        //向list集合每个dict对象中设置hasChildren
        for (Dict dict : dictList) {
            Long dictId = dict.getId();
            //指的是当前类
            boolean ischildren = this.isChildren(dictId);
            dict.setHasChildren(ischildren);
        }
        return dictList;
    }

    /**
     * 导出
     *
     * @param response
     */
    @Override
    public void exportData(HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        //URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        try {
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            List<Dict> dictList = dictMapper.selectList(null);

            if (!CollectionUtils.isEmpty(dictList)) {
                LOG.info("数据字典的数据_dictList:{}", dictList);
            }

            //数组长度固定
//            List<DictEevo> dictVoList = new ArrayList<>(dictList.size());
            List<DictEevo> dictVoList = new ArrayList<>();
            for (Dict dict1 : dictList) {
                DictEevo dictEevo = new DictEevo();
                BeanUtils.copyProperties(dict1, dictEevo);
                dictVoList.add(dictEevo);
            }

            EasyExcel.write(response.getOutputStream(), DictEevo.class)
                    .sheet("dict数据字典").doWrite(dictVoList);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * 下载模板
     *
     * @param response
     */
    @Override
    public void downloadTemplate(HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        //URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        try {
            String fileName = URLEncoder.encode("下载模板", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            List<DictEevo> dictVoList = new ArrayList<>();
            if (CollectionUtils.isEmpty(dictVoList)) {
                LOG.info("数据字典的数据_dictVoList:{}", dictVoList);
            }

            EasyExcel.write(response.getOutputStream(), DictEevo.class)
                    .sheet("下载模板").doWrite(dictVoList);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入数据字典
     * allEntries :所有条目
     * CacheEvict ：缓存驱逐赶出清空
     *
     * @param file
     */
    @CacheEvict(value = "dict", allEntries = true)
    @Override
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEevo.class, new DictListener(baseMapper))
                    .sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 获取数据字典名称
     *
     * @param dictCode
     * @param value
     * @return
     */
    @Override
    public String getDictName(String dictCode, String value) {
        //如果dictCode为空，直接根据value查询
        if (StringUtils.isEmpty(dictCode)) {
            //直接根据value查询
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value", value);
            Dict dict = baseMapper.selectOne(wrapper);
            return dict.getName();
        } else {
            //如果dicCode不为空，根据dicCode和value查询
            //根据dicCode查询dict对象，得到dict的id值
            Dict codeDict = this.getDictByDictCode(dictCode);
            Long parent_id = codeDict.getId();
            //根据parent_id和value进行查询

            QueryWrapper<Dict> wapper = new QueryWrapper<Dict>().eq("parent_id", parent_id)
                    .eq("value", value);
            Dict finalDict = baseMapper.selectOne(wapper);
            return finalDict.getName();
        }
    }

    /**
     * 根据dictCode获取下级节点
     *
     * @param dictCode
     * @return
     */
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //根据dictCode获取对应id
        Dict dict = this.getDictByDictCode(dictCode);
        //根据id获取子节点
        List<Dict> childData = this.findChildData(dict.getId());

        return childData;
    }

    /**
     * 根据dictCode查询dict对象
     *
     * @param dictCode
     * @return
     */
    private Dict getDictByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code", dictCode);
        Dict codeDict = baseMapper.selectOne(wrapper);
        //  List<Dict> dicts = baseMapper.selectList(wrapper);
        //  Dict codeDict = dicts.get(0);
        return codeDict;
    }


    //判断id下面是否有子节点
    //写个私有的方法，只能自己用的，来判断，是否有子节点
    private boolean isChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(wrapper);
        //0>0 1>0
        return count > 0;
    }
}
